package com.googlecode.lookie.platform.settings;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.richclient.settings.Settings;
import org.springframework.richclient.settings.SettingsException;
import org.springframework.richclient.settings.SettingsManager;
import org.springframework.richclient.settings.TransientSettingsFactory;

public class LookieSettingsManager
    extends SettingsManager
    implements InitializingBean
{

    private static final Logger logger = LoggerFactory.getLogger( LookieSettingsManager.class );

    private boolean fallback;

    private boolean fallbackOnError;

    public boolean isFallback()
    {
        return fallback;
    }

    public boolean isFallbackOnError()
    {
        return fallbackOnError;
    }

    public void setFallbackOnError( boolean fallbackOnError )
    {
        this.fallbackOnError = fallbackOnError;
    }

    public Settings getInternalSettings()
    {
        Settings settings = null;
        try
        {
            settings = super.getInternalSettings();
        }
        catch ( SettingsException e )
        {
            // this should never occur
            logger.warn( "exception getting internal settings", e );
        }
        return settings;
    }

    public Settings getUserSettings()
    {
        Settings settings = null;
        try
        {
            settings = super.getUserSettings();
        }
        catch ( SettingsException e )
        {
            // this should never occur
            logger.warn( "exception getting user settings", e );
        }
        return settings;
    }

    public void afterPropertiesSet()
        throws SettingsException
    {
        try
        {
            super.getInternalSettings();
            super.getUserSettings();
        }
        catch ( SettingsException e )
        {
            if ( isFallbackOnError() )
            {
                logger.warn( "exception initializing settings", e );
                fallback = true;
            }
            else
            {
                throw e;
            }
        }

        if ( !fallback )
        {
            setSettingsFactory( new TransientSettingsFactory() );
            try
            {
                super.getInternalSettings();
                super.getUserSettings();
            }
            catch ( SettingsException e )
            {
                logger.warn( "exception initializing fallback settings", e );
                // should not occur because we using TransientSettingsFactory which does not throw exceptions
            }
        }
    }

}
